  <template>
  <div class="list">
    <div class="content-head" style="margin-bottom: 20px;">
      <div class="sort-keys">

        <div class="tab-list">
           <div class="item" @click="status = item.key" :class="{actived: status === item.key}"
             v-for="(item, index) in statusList">
             {{item.text}}
             ({{statusTotal[item.key]}})
           </div>
         </div>


        <a-input-search placeholder="输入关键字" enter-button  style="width: 180px;margin-right:10px;" v-model="key" allowClear :size="size"
          @input="onSearch" @search="onSearch" />

        <router-link to="/activity/maoxian/setting" style="margin: 0px 10px;">冒险岛配置</router-link>

      </div>
      <a-button type="primary" icon="plus" @click="handleCreate" v-if="!selectMode">创建{{resourceTypeText}}</a-button>
    </div>
    <a-table class="table" :rowKey="row => row.uuid" :dataSource="list" :pagination="pagination" :size="size">
      <a-table-column title="标题" width="180px">
        <template slot-scope="row">
          <div class="title-c">
            <img class="thumb" :src="row.thumb" />
            <div class="right">
              <div class="title">{{row.title}}</div>
              <!-- <div style="margin: 4px 0px;">{{row.uuid}}</div> -->
              <PriceDisplay :info="row"></PriceDisplay>
              <!-- <div class="time"> {{$tool.formatDate(row.start_at, 'MM-dd hh:mm')}}</div>
              <div class="time" v-if="">{{$tool.formatDate(row.end_at, 'MM-dd hh:mm')}}</div> -->
              <a-tag color="blue" style="margin-left:10px;" v-if="row.client_type === 1">小程序</a-tag>
              <a-tag color="red" style="margin-left:10px;" v-else-if="row.client_type === 2">APP</a-tag>
            </div>
          </div>
        </template>
      </a-table-column>
      <!-- <a-table-column title="价格" width="120px">
        <template slot-scope="row">
          <PriceDisplay :info="row" v-if="row.is_need_pay"></PriceDisplay>
          <div v-else>免费</div>
        </template>
      </a-table-column> -->
      <a-table-column title="利润率" width="280px">
        <template slot-scope="row" v-if="row.lr">
          除秘境利润率:{{row.lr.lr}}%<br>
          秘境每发需抽:{{row.lr.cs}}次<br>
          秘境每次成本:{{row.lr.csall/100}}元<br>
          当前秘境成本:{{row.lr.lingli_cb/100}}元<br>
          总利润率:{{row.lr.lr2}}%<br>
        </template>
      </a-table-column>
      <a-table-column title="额外扩展" width="280px">
        <template slot-scope="row">
          <div>
          <span>总销售金额:{{row.a / 100}}</span><br>
          <span>支付实付:{{row.b / 100}}</span><br>
          <span>支付红包:{{row.c / 100}}</span><br>
          <span>支付积分:{{row.d}}</span><br>
          <span>消耗优惠券:{{row.e / 100}}</span><br>
          <span>总价值:{{row.f / 100}}</span><br>
          <span>总抽数:{{row.h}}</span><br>
          <span>利润:{{row.lr2 / 100}}</span>
          </div>
        </template>
      </a-table-column>
      <a-table-column title="库存/销量" width="110px">
        <template slot-scope="row">
           <div class="stock">库存: {{row.stock}}</div>
           <div class="stock">销量: {{row.sales}}</div>
        </template>
      </a-table-column>
      <a-table-column title="奖品等级" width="100px">
        <template slot-scope="row">
           {{row.sku_level.filter(i => {return i.status === 1}).length}}等级
            <a href="javascript:;" @click="handleEditSkuLevel(row)">
              编辑
            </a>
        </template>
      </a-table-column>
      <a-table-column width="280px">
        <div slot="title">
          奖品池
          <tips>回血池的奖品只有当用户的亏损值达到设置的亏损线后才会开出</tips>
        </div>
        <template slot-scope="row">
          <template v-for="n in 5">
            <div v-if="row.sku_level[n-1].status" style="margin-bottom: 4px;">
              <span class="level-title" style="margin-right: 10px;">{{row.sku_level[n-1].title}}</span>
              <span class="level-odds" style="margin-right: 10px;">{{row.sku_level[n-1].odds}}%</span>
              <a href="javascript:;" @click="handleEditSkuList(row, n)">
                <span class="">{{row.sku_level[n-1] && row.sku_level[n-1].sku_total}}种奖品</span>
              </a>
              <span class="" style="margin-left: 10px;">{{row.sku_level[n-1].sku_sales}}销量</span>
              <span class="" style="margin-left: 10px;color:red;" v-if="row.sku_level[n-1].not_sku_stock > 0">{{row.sku_level[n-1].not_sku_stock}}剩余</span>
              <span class="" style="margin-left: 10px;color:fuchsia;" v-if="row.sku_level[n-1].not_sku_stock < -1">超出</span>
              <span class="" style="margin-left: 10px;">{{row.sku_level[n-1].sku_stock}}库存</span>
            </div>
          </template>

          <div style="margin-bottom: 4px;" class="add-blood-row">
            <span class="level-title" style="margin-right: 10px;">灵力池</span>
            <span class="level-odds" style="margin-right: 10px;"></span>
            <a href="javascript:;" @click="handleEditSkuList(row, 6)">
                <span class="">{{row.sku_level[5].sku_total}}种奖品</span>
            </a>
            <span class="" style="margin-left: 10px;">{{row.sku_level[5].sku_sales}}销量</span>
            <span class="" style="margin-left: 10px;">{{row.sku_level[5].sku_stock}}库存</span>
          </div>
          <div style="margin-bottom: 4px;" class="add-blood-row">
            <span class="level-title" style="margin-right: 10px;">SP池</span>
            <span class="level-odds" style="margin-right: 10px;"></span>
            <a href="javascript:;" @click="handleEditSkuList(row, 7)">
                <span class="">{{row.sku_level[6].sku_total}}种奖品</span>
            </a>
            <span class="" style="margin-left: 10px;">{{row.sku_level[6].sku_sales}}销量</span>
            <span class="" style="margin-left: 10px;">{{row.sku_level[6].sku_stock}}库存</span>
          </div>
        </template>
      </a-table-column>
      <a-table-column title="计划任务" width="80px" v-if="action_show">
        <template slot-scope="row">
          <a href="javascript:;" @click="handleEditRobotList(row)">
            <span class="">{{row.task_total}}个计划任务</span>
          </a>
        </template>
      </a-table-column>
      <a-table-column title="排序" width="80px" v-if="!selectMode">
        <template slot-scope="row">
          {{row.list_weight}}
          <span @click="handleEditListWeight(row)" style="margin-left: 10px;"><a href="javascript:;">
              <a-icon type="edit" />
            </a></span>
        </template>
      </a-table-column>
      <a-table-column title="上/下架" width="60px" v-if="!selectMode">
        <template slot-scope="row">
          <ISwitch :value="row.status" :active="1" :unactive="0" @change="listedStatusChange($event, row)" />
        </template>
      </a-table-column>
      <a-table-column title="创建日期" width="100px">
        <template slot-scope="row">
          <span>{{$tool.showShortTime(row.created_at)}}</span>
        </template>
      </a-table-column>
      <a-table-column title="操作" width="180px" v-if="!selectMode">
        <template slot-scope="row">
          <span>
            <a href="javascript:;" @click="getPath(row)">预览/路径</a>
            <a-divider type="vertical" />
            <a href="javascript:;" @click="handleCopy(row)">复制</a>
            <a-divider type="vertical" />
            <a href="javascript:;" @click="handleEdit(row)">编辑</a>
            <div style="margin-top: 10px;">
              <a href="javascript:;" @click="handleDelete(row)">删除</a>
              <a-divider type="vertical" />
              <a href="javascript:;" style="color: red;" @click="handleTestLottery(row)">模拟测试</a>
            </div>
          </span>
        </template>
      </a-table-column>
    </a-table>

    <a-modal :title="(editUuid ? '编辑' : '创建') + resourceTypeText" style="top: 100px;" :visible="isEdit" width="1000px"
      @cancel="isEdit = false" :footer="null">
      <Edit v-if="isEdit" :uuid="editUuid" @cancel="isEdit = false" @success="fetchData" />
    </a-modal>

    <EditSkuList :info="current" :currentSkuLevel="currentSkuLevel" v-if="isEditSkuList" @refresh="fetchData" @close="isEditSkuList = false"></EditSkuList>

    <EditSkuLevel :info="current" v-if="isEditSkuLevel" @refresh="fetchData" @close="isEditSkuLevel = false"></EditSkuLevel>
    <EditWordLevel :info="current" v-if="isEditWordLevel" @refresh="fetchData" @close="isEditWordLevel = false"></EditWordLevel>
    <EditRobotList :info="current" v-if="isEditRobotList" @refresh="fetchData" @close="isEditRobotList = false"></EditRobotList>

  </div>
</template>
<script>
  import moment from 'moment'
  import ISwitch from '@/components/ISwitch/ISwitch'

  import Edit from "./Edit.vue"

  import EditSkuList from './components/EditSkuListPopup.vue'
  import EditSkuLevel from './components/EditSkuLevelPopup.vue'
  import EditWordLevel from './components/EditWordLevelPopup.vue'
  import EditRobotList from '@/views/robot/Maoxian/components/EditRobotListPopup.vue'


  const resourceType = 'maoxians'
  const resourceTypeText = '冒险岛'

  export default {
    components: {
      ISwitch,
      Edit,
      EditSkuList,
      EditSkuLevel,
      EditWordLevel,
      EditRobotList,
    },
    props: {
      selectMode: {
        type: Boolean
      },
      params: {
        type: Object
      },
      size: {
        type: String,
        default: 'default'
      },
      type: {
        type: String,
        default: ''
      },
    },
    data() {
      return {
        action_show: false,
        isEdit: false,
        editUuid: '',
        current: {},
        isEditSkuLevel: false,
        isEditWordLevel: false,
        isEditSkuList: false,
        isEditRobotList: false,
        currentSkuLevel: 1,
        resourceTypeText,
        exportOptions: {
          status: 'all',
          startTime: '',
          endTime: '',
          type: 'normal'
        },
        status: 'unexpired',
        list: [],
        page: 1,
        per_page: 10,
        total: 0,
        key: '',
        statusList: [
          {
            text: '上架中',
            key: 'on_stock'
          },
          {
            text: '已下架',
            key: 'off_stock'
          },
          {
            text: '售罄',
            key: 'sell_out'
          }
        ],
        status: 'on_stock',
        statusTotal: {
          on_stock: 0,
          off_stock: 0,
          sell_out: 0,
          marked: 0
        },
      }
    },
    watch: {
      params() {
        this.refreshData()
      },
      type() {
        this.refreshData()
      },
      status () {
        this.page = 1
        this.refreshData()
      }
    },
    computed: {
      pagination() {
        return {
          defaultPageSize: this.per_page,
          defaultCurrent: this.page,
          total: this.total,
          onChange: (e) => {
            this.page = e
            // this.per_page = e.pageSize
            this.fetchData()
          }
        }
      }
    },
    filters: {},
    created() {
      this.action_show = this.$authCheck('maoxianList')
      this.fetchData()
      // this.getCategoryList()
    },
    methods: {
      handleEditRobotList(row, level) {
        this.current = row
        this.isEditRobotList = true
      },
      handleCopy(row) {
        this.$confirm({
          title: '确定复制吗',
          content: `将复制一个新活动到已下架状态栏`,
          onOk: () => {
            this.$http.post(`/${resourceType}/${row.uuid}/copy`).then(res => {
              this.$message.success('复制成功，请在“已下架”列表中编辑活动');
              this.status = 'off_stock'
              this.fetchData()
            })
          }
        })
      },
      fetchTotalData() {
        this.$http('/status-total/activity/maoxian').then((res) => {
          this.statusTotal = res.data.total
        })
      },
      handleEditSkuList(row, level) {
        this.current = row
        this.currentSkuLevel = level
        this.isEditSkuList = true
      },
      getPath(row) {
        this.$getPathPopup.show({
          page: '/pages/maoxiandao/detail',
          param: 'uuid=' + row.uuid
        })
      },
      handleDelete(row) {
        this.$confirm({
          title: '提示',
          content: `确认删除吗？`,
          onOk: () => {
            this.$http.delete(`/${resourceType}/${row.uuid}`).then(res => {
              this.fetchData()
            })
          }
        })
      },
      updateItem(row, data) {
        return this.$http.patch(`/${resourceType}/${row.uuid}`, {
          type: 'update',
          attributes: {
            ...data
          }
        })
      },
      listedStatusChange(e, row) {
        this.updateItem(row, {
          status: e
        }).then(res => {
          this.fetchData()
        })
      },
      handleEditSkuLevel (row) {
        this.current =  row
        this.isEditSkuLevel = true
      },
      handleEditWordLevel (row) {
        this.current =  row
        this.isEditWordLevel = true
      },
      handleEditListWeight(row) {
        this.$globalForm.show({
          title: '编辑排序',
          items: [{
            type: 'number',
            key: 'list_weight',
            title: '排序',
            default: row.list_weight,
            required: true
          }, ],
          success: (data) => {
            this.updateItem(row, {
              ...data
            }).then(res => {
              this.$message.success('保存成功');
              this.$globalForm.hide()
              this.fetchData()
            })
          }
        })
      },
      handleTestLottery(row) {
        this.$iForm.show({
          title: '活动模拟开盒测试',
          frame: [
            {
              type: 'text',
              title: '重要说明',
              text: '<span style="color: red;">请谨慎使用此功能，不要使用在正式版上！</span> <br/>模拟测试仅会统计并记录对应奖品的销量，但不会保存模拟的开盒订单数据。',
            },
            {
              type: 'text',
              title: '作用',
              text: '此功能仅用于测试各奖品的真实开盒概率是否与设置的概率相符。',
              span: 24,
            },
            {
              title: '要模拟开盒的个数',
              key: 'total',
              type: 'number',
              tips: '如5000， 系统会自动随机拆分为每次1-4个数量的连开'
            },
          ],
          success: (data) => {
            this.$http.post(`/maoxians/${row.uuid}/test-lottery`, {
              ...data
            }).then(res =>  {
              this.$message.success('模拟成功');
              this.fetchData()
              this.$iForm.hide()
            })
          }
        })
      },
      handleCreate() {
        this.editUuid = ""
        this.isEdit = true
      },
      handleEdit(row) {
        this.editUuid = row.uuid
        this.isEdit = true
      },
      refreshData() {
        this.page = 1
        this.key = ''
        this.fetchData()
      },
      onSearch(e) {
		  this.page = 1
        this.fetchData()
        // clearTimeout(this.timeout)
        // this.timeout = setTimeout(() => {
        //   this.fetchData()
        // }, 300)
      },
      fetchData() {
        this.isEdit = false
        this.$http.get(`/${resourceType}`, {
          params: {
            // type: activityType,
            status: this.status,
            ...this.params,
            page: this.page,
            per_page: this.per_page,
            // type: this.type,
            key: this.key,
          }
        }).then(res => {
          this.list = res.data.list
          this.total = res.data.item_total
        }).finally(() => {
          this.fetchTotalData()
          this.loading = false
        })
      },
      getCategoryList() {
        this.$api.emit('category.list', 'article').then(res => {
          this.category = res.data.list
        })
      },
    }
  }
</script>
<style lang="scss" scoped>
  .content-head {
    display: flex;
    justify-content: space-between;
    flex-wrap: wrap;
  }

  .level-title {
    // font-size: 100%;
    font-weight: 500;
  }

  .sort-keys {
    display: flex;
    align-items: center;

    .tab-list {
      display: flex;
      margin-top: 6px;
      border-bottom: 1px solid #e1e1e1;
      margin-right: 50px;

      .item {
        margin-right: 30px;
        padding: 0px 10px 4px 10px;
        cursor: pointer;
        font-weight: 500;

        &.actived {
          color: #1890FF;
          border-bottom: 3px solid #1890FF;
        }

        &:hover {
          color: #1890FF;
        }
      }
    }

  }

  .table {

    .title-c {
      display: flex;
      align-items: center;

      .thumb {
        margin-right: 10px;
        height: 60px;
        border-radius: 6px;
      }

      .title {
        font-weight: 500;
        min-height: 30px;
      }

      .time {
        color: gray;
        font-size: 80%;
      }
    }
  }

  .add-blood-row {
    background: #f1f1f1;
    padding: 10px 10px;
    position: relative;
    left: -10px;
  }
</style>
